﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Vibes.Common.Interfaces;
using Vibes.Common.Extensions;

namespace Vibes.Web.Mvc
{
    public class IocContainerControllerFactory : DefaultControllerFactory
    {
        private readonly IIocContainer _container;

        public IocContainerControllerFactory(IIocContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            _container = container;
        }

        public override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            var type = GetControllerType(requestContext, controllerName);
            if (type == null)
            {
                throw new InvalidOperationException("No such controller for {0}".format(controllerName));
            }

            IController controller = null;
            try
            {
                controller = (IController)_container.Resolve(type);
            }
            catch
            {
                controller = (IController)Activator.CreateInstance(type, _container);
            }
            return (IController)Activator.CreateInstance(type, _container);
        }
    }
}
